// taro
import Taro, { useShareAppMessage, useShareTimeline } from "@tarojs/taro";
import { View, WebView } from "@tarojs/components";

// ui
import {
  Avatar,
  Cell,
  ConfigProvider,
  Toast,
  Loading,
  Dialog,
  ImagePreview,
} from "@nutui/nutui-react-taro";
import {
  ArrowRight,
  Setting,
  Transit,
  Phone,
  Close,
  Ask,
} from "@nutui/icons-react-taro";

import "./index.scss";

import { useEffect,  useRef,  useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  changeMember_id,
  changeOpenid,
  changeUser,
  myWxInfo,
  phoneOpenid,
  storeMember_id,
  storeUser,
} from "@/redux/userSlice";

import { ApiCheckLogin, ApiGetOpenId, ApiLogout, ApiMemberInfo } from "@/utils/api";
import wxImg from "../../assets/wx.jpg";



const home = () => {
  // 导入仓库 2.使用属性
  const storeMemberId = useSelector(storeMember_id);
  const user = useSelector(storeUser);
  const myOpenid = useSelector(phoneOpenid);
  const WxInfo = useSelector(myWxInfo);
  const dispatch = useDispatch();
  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }

    return {
      title: "东进广场",
      path: "pages/home/index", //?id=123
      imageUrl: "../../assets/home.jpg",
    };
  });
  // 全局朋友圈分享配置
  // useShareTimeline(() => {
  //   return {
  //     title: "东进广场",
  //     query: "id=123",
  //   };
  // });
  useEffect(() => {
    // 获取用户信息
    if (Taro.getStorageSync("img")) {
      setImg(Taro.getStorageSync("img") as string);
    } else if (WxInfo.avatarUrl) {
      setImg(WxInfo.avatarUrl);
    }
  }, [Taro.getStorageSync("img"), WxInfo.avatarUrl]);

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);

  // loadding
  const [loading, setLoading] = useState(true);
  const [isMember, setIsMember] = useState(0); //

  const [visible, setVisible] = useState(false);
  // 用户填写信息
  const [formData, setFormData] = useState({
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    captcha: "",
    member_car_plate_number: "",
    created_at: "",
    free_parking_expire_at: "",
  });

  // 请求登录状态------
  const checkLogin = async () => {
    // 没有openid 获取openid
    if (!myOpenid) {
      // 去到注册页
      // 显示为未注册逻辑
      setIsMember(0);
      // setLoading(false)
      // Taro.getSetting：获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
      getOpenIdFn();
      return;
    }

    // 有openid
    let res;
    console.log(myOpenid, "myOpenid---"); //
    if (storeMemberId) {
      // res = await ApiCheckLogin(myOpenid, 1);
      await getMemberInfo(Number(storeMemberId));
      return;
    } else {
      try {
        res = await ApiCheckLogin(myOpenid, 1);
        console.log(res.data.member_id, "member_id1");
      } catch (error) {
        res = error;
        setIsMember(0);
        setLoading(false);
        ApiLogout();
        console.error("ApiLogout 2");
        Taro.clearStorageSync();
      }

      if (res.code === 0) {
        await getMemberInfo(res.data.member_id);
        // 当前页面使用
        setMember_id(res.data.member_id);
        dispatch(changeMember_id(res.data.member_id));
        setIsMember(1);
      } else if (res.code == 1 || res.code == 2001 || res.code == 2006) {
        await ApiLogout();
        console.warn(res.msg, res.code, "ApiCheckLogin");
        Taro.clearStorageSync();
        setIsMember(0);
        setLoading(false);
      } else {
        setLoading(false);
        console.log("未登录", res.msg);
        setIsMember(0);
        setLoading(false);
        // await ApiLogout();
        // localStorage.clear();
        return;
      }
    }
  };

  // wx------
  // 授权获取openid
  const getOpenIdFn = () => {
    Taro.getSetting({
      success: async (res) => {
        if (res.authSetting["scope.userInfo"]) {
          // 用户已经授权过，可以直接获取用户信息
          // getUserInfo();
          // 获取openid
          getopenId();
        } else {
          // 用户未授权，需要弹出授权窗口
          showAuthModal();
        }
      },
    });
  };

  // 授权设置页面
  const openSetting = () => {
    // Taro.openSetting：调起客户端小程序设置界面，返回用户设置的操作结果。设置界面只会出现小程序已经向用户请求过的权限。
    Taro.openSetting({
      success: (res) => {
        if (res.authSetting["scope.userInfo"]) {
          // 用户授权成功，可以获取用户信息
          // getUserInfo();
        } else {
          // 用户拒绝授权，提示授权失败
          Taro.showToast({
            title: "授权失败",
            icon: "none",
          });
        }
      },
    });
  };

  // 授权窗口
  const showAuthModal = () => {
    Taro.showModal({
      title: "授权提示",
      content: "需要获取您的用户信息",
      confirmText: "去授权",
      cancelText: "取消",
      success: (res) => {
        if (res.confirm) {
          // 用户点击确认，打开授权设置页面
          openSetting();
        }
      },
    });
  };
  const [registerForm, SetRegisterForm] = useState({
    openid: Taro.getStorageSync("openid") || "",
    sessionKey: Taro.getStorageSync("sessionKey") || "",
  });

  // 获取openid
  const getopenId = () => {
    console.log("获取openid");
    Taro.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          // 测试
          //   const url = config.url(res.code);
          //   Taro.request({
          //   url,
          //   success:async(res) => {
          //    const data  = res.data;
          //    console.log(res.data, "data");
          //    const myRegisterForm = {
          //      openid: data.openid,
          //      sessionKey: data.session_key,
          //    };
          //    SetRegisterForm(myRegisterForm);
          //    console.log(myRegisterForm, "myRegisterForm");
          //    //  存储新的加密令牌
          //    Taro.setStorageSync("openid", data.openid);
          //    Taro.setStorageSync("sessionKey", data.session_key);
          //    // 存到仓库
          //    dispatch(changeOpenid(data.openid));
          //    // loading结束
          //    const openid = data.openid;
          //    let loginRes;
          //    console.log("ApiLogout 1");
          //    try {
          //      console.log("ApiCheckLogin");
          //      loginRes = await ApiCheckLogin(openid, 1);
          //      console.log(loginRes.data.member_id, "member_id1");
          //    } catch (error) {
          //      loginRes = error;
          //      console.error("ApiCheckLogin catch", error);
          //      // ApiLogout();
          //      // Taro.clearStorageSync();
          //    }
          //    if (loginRes.code === 0) {
          //      await getMemberInfo(loginRes.data.member_id);
          //      setIsMember(1);
          //      // 当前页面使用
          //      setMember_id(loginRes.data.member_id);
          //      dispatch(changeMember_id(loginRes.data.member_id));
          //      setLoading(false);
          //    } else {
          //      console.log("ApiCheckLogin else");
          //      setIsMember(0);
          //      setLoading(false);
          //      return;
          //    }
          //  }
          //   });

          // 正式
          ApiGetOpenId(res.code).then(async (res) => {
            const { data } = res.data;
            // console.log(res.data, "data");
            const myRegisterForm = {
              openid: data.openid,
              sessionKey: data.session_key,
            };
            SetRegisterForm(myRegisterForm);
            console.log(myRegisterForm, "myRegisterForm");
            //  存储新的加密令牌
            Taro.setStorageSync("openid", data.openid);
            Taro.setStorageSync("sessionKey", data.session_key);
            // 存到仓库
            dispatch(changeOpenid(data.openid));
            // loading结束
            const openid = data.openid;
            let loginRes;
            console.log("ApiLogout 1");
            // try {
            //   await ApiLogout();
            // } catch (error) {
            //    setLoading(false)
            //    setIsMember(0);
            // }
            try {
              console.log("ApiCheckLogin");
              loginRes = await ApiCheckLogin(openid, 1);
              console.log(loginRes.data.member_id, "member_id1");
            } catch (error) {
              loginRes = error;
              console.error("ApiCheckLogin catch", error);
              // ApiLogout();
              // Taro.clearStorageSync();
            }
            if (loginRes.code === 0) {
              await getMemberInfo(loginRes.data.member_id);
              setIsMember(1);
              // 当前页面使用
              setMember_id(loginRes.data.member_id);
              dispatch(changeMember_id(loginRes.data.member_id));
              setLoading(false);
            } else {
              console.log("ApiCheckLogin else");
              setIsMember(0);
              setLoading(false);
              return;
            }
          });
        } else {
          console.log("登录失败！" + res.errMsg);
          // loading结束
        }
      },
    });
  };

  // 修改user对象属性值------
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log(fieldName, value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };

  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
  };

  // 获取会员详情信息
  const getMemberInfo = async (member_id2?: number) => {
    let my_member_id = member_id2 ? member_id2 : member_id;
    console.log(my_member_id, "my_member_id");
    if (!myOpenid && !Taro.getStorageSync("openid")) {
      console.log("需重新进入");
      console.log(myOpenid, "myOpenid");
      return;
    }

    // 请求用户信息
    // 校验是否有
    let resInfo;
    console.log(user, "user");
    if (!user.mobile) {
      try {
        resInfo = await ApiMemberInfo(my_member_id);
      } catch (err) {
        resInfo = err;
        console.log(err, "err");
      } finally {
        // 无论请求成功或失败，都设置 loading 为 false
        // 使用骨架屏
        setLoading(false);
      }
      console.log(resInfo, "resInfo");
      if (resInfo.code != 0) {
        console.log("请求用户信息失败");
        setIsMember(0);
        return;
      } else {
        setIsMember(1);
      }
      console.log("111");

      // 没有请求,存仓库
      dispatch(changeUser(resInfo.data));
      const {
        name,
        mobile,
        sex,
        birthday,
        member_car_plate_number,
        created_at,
        free_parking_expire_at,
      } = resInfo.data;
      // 更新
      handleNameInputChange("name", name);
      handleNameInputChange("mobile", mobile);
      handleNameInputChange("sex", sex);
      handleNameInputChange(
        "member_car_plate_number",
        member_car_plate_number || "未绑定"
      );
      handleNameInputChange("created_at", created_at);
      handleNameInputChange("free_parking_expire_at", free_parking_expire_at);
      handleNameInputChange(
        "birthday",
        birthday && new Date(birthday.replace(/-/g, "/"))
      );
      console.log(member_car_plate_number);
      if (!member_car_plate_number) {
        Toast.show("test", {
          title: "尊贵的会员,请绑定车牌号,即可获得4小时免费停车权限",
          duration: 3.5,
        });
      }
    } else {
      setIsMember(1);
      setLoading(false);
      // 从仓库读取
      // console.log(user, "user");
      // 更新用户对象
      const {
        name,
        mobile,
        sex,
        birthday,
        member_car_plate_number,
        created_at,
        free_parking_expire_at,
      } = user;
      handleNameInputChange("name", name);
      handleNameInputChange("mobile", mobile);
      handleNameInputChange("sex", sex);
      handleNameInputChange(
        "member_car_plate_number",
        member_car_plate_number || "未绑定"
      );
      handleNameInputChange("created_at", created_at);
      handleNameInputChange("free_parking_expire_at", free_parking_expire_at);
      handleNameInputChange(
        "birthday",
        birthday && new Date(birthday.replace(/-/g, "/"))
      );
    }
    // form.setFieldsValue(formData);
    return resInfo;
  };

  const year = () => {
    const userYear = new Date(
      formData.free_parking_expire_at &&
        formData.free_parking_expire_at.replace(/-/g, "/")
    ).getFullYear();
    const nowYear = new Date().getFullYear();
    if (userYear - nowYear) {
      return "长期";
    } else {
      return formData.free_parking_expire_at;
    }
  };

  // 在组件中添加 ref
  const timerRef = useRef<number | null>(null);
  // 在 useEffect 中清除上一次的定时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  // 在页面加载时从localStorage获取图像数据
  const initialImg = Taro.getStorageSync("img") || "";
  const [img, setImg] = useState<string>(initialImg);
  const [init, setInit] = useState<boolean>(false);

  // 未注册------
  const noneRegister = async () => {
    Dialog.open("dialog", {
      title: "未注册会员",
      content: "成为会员可4小时免费停车,是否前往注册?",
      // content: "(成为会员可4小时免费停车),是否前往注册?",
      // 确认修改
      onConfirm: () => {
        Dialog.close("dialog");
        Taro.navigateTo({
          url: "/pages/user/index",
        });
      },
      onCancel: () => {
        Dialog.close("dialog");
      },
    });
  };

  // 定义一个状态用于保存 WebView 的链接
  // const [webSrc, setWebSrc] = useState(""); // 初始为空
  //   停车缴费
  const carFree = () => {
    console.log("去缴费");
    // const externalLink = "https://djc.dgruiyikeji.com/toOrderWx";
    // setWebSrc(externalLink);
    Taro.navigateToMiniProgram({
      // appId: "",
      shortLink: "#小程序://捷停车/iuHV6TRCrtgG2rz",
      // enwVersion: "release",
      // path: "",
    });
  };
  // 确定注册手机
  const determine = async () => {
    Taro.reLaunch({
      url: "/pages/user/index",
    });
  };

  // 挂载页面
  useEffect(() => {
    checkLogin();
  }, []);
  // 挂载页面

  const darkTheme = {
    nutuiColorPrimaryStop1: "#1677ff",
    nutuiColorPrimaryStop2: "#1677ff",
  };
  return (
    <View>
      <View style={{ opacity: loading ? 0 : 1 }}>
        <View>
            <View className="big_box">
              <View
                className="home_title"
                onClick={() => {
                  setVisible(false);
                }}
              >
                {/* 个人中心背景 */}
                <View className="bg">
                  {/* bgMount && */}
                  {<View className="blue_bg"></View>}
                  {/* <img onLoad={()=>{console.log('加载完成');
              }} src="../../../public/bg.jpg" className="blue_bg"></img> */}
                </View>
              </View>
              {/* 中间卡片 */}
              <View className="card_box">
                <View className="center">
                  <Cell className="card">
                    <View className="cardInfo">
                      <View className="car_item" onClick={() => {
                            Taro.navigateTo({
                              url: "/pages/tree/index",
                            });
                          }}>
                        <span
                          className="test"
                        >
                          我要捐款种树
                        </span>
                      </View>
                    </View>
                  </Cell>
                </View>
              </View>
            </View>
        </View>
      </View>
    </View>
  );
};

export default home;
